package kadledav.portlet.detail;

import javax.persistence.EntityNotFoundException;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.RenderRequest;

import kadledav.backend.dto.NewsDTO;
import kadledav.backend.service.NewsService;
import kadledav.portlet.ParameterConstants;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.annotation.EventMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

@Controller
@RequestMapping("VIEW")
public class DetailPortlet {
	private static final Logger logger = Logger.getLogger(DetailPortlet.class);

	@Autowired
	private NewsService newsService;

	@RenderMapping
	public ModelAndView defaultRenderer(RenderRequest request) {
		Object currentId = request.getPortletSession().getAttribute(DetailConstants.CURRENT_ID);
		if(currentId!=null){
			return showDetail(Integer.valueOf(currentId.toString()));
		}
		logger.info("Detail view renderer - no current news");
		return new ModelAndView(DetailConstants.JSP_VIEW_EMPTY);
	}

	@RenderMapping(params = ParameterConstants.NEWS_ID)
	public ModelAndView showDetail(Integer newsId) {
		logger.info("Detail view renderer - current news id: " + newsId);
		NewsDTO news = null;
		try {
			news = newsService.findById(Integer.valueOf(newsId));
			logger.warn("News with id " + newsId + " was not found");
		} catch (EntityNotFoundException e) {
			return new ModelAndView(DetailConstants.JSP_VIEW_NOT_FOUND);
		}
		ModelAndView modelAndView = new ModelAndView(DetailConstants.JSP_VIEW);
		modelAndView.addObject(DetailConstants.ONE_NEWS, news);
		return modelAndView;
	}

	// @EventMapping(value="{http://kadledav/events}news.id")
	@EventMapping(value = "news.id")
	public void processNewsEvent(EventRequest eventRequest, EventResponse eventResponse) {
		logger.debug("Processing newsId event");
		String newsId = (String) eventRequest.getEvent().getValue();
		eventRequest.getPortletSession().setAttribute(DetailConstants.CURRENT_ID, newsId);
		logger.trace("News id event processed with value - " + newsId);
	}

}
